package fiszki.namespace;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class SetsDBAdapter {
	public static final int ID_COLUMN = 0;
    public static final int NAME_COLUMN = 1;
    public static final int QUESTIONLANG_COLUMN = 2;
    public static final int ANSWERLANG_COLUMN = 3;
    public static final int ANSWER_COLUMN = 3;
    
    private SQLiteDatabase db;
    private Context context;
    private DatabaseHelper dbHelper;
    
	public SetsDBAdapter(Context context) {
	    this.context = context;
	}
	
	public SetsDBAdapter open() {
	    dbHelper = new DatabaseHelper(context, null);
	    
	    try {
	        db = dbHelper.getWritableDatabase();
	    } 
	    catch (SQLException e) {
	        db = dbHelper.getReadableDatabase();
	    }
	    return this;
	}
	
	public void close() {
	    dbHelper.close();
	}
	
	public long addSet(String name, String questionLang, String answerLang) {
	    ContentValues newSetValues = new ContentValues();
	    
	    newSetValues.put("name", name);
	    newSetValues.put("questionlang", questionLang.toString());
	    newSetValues.put("answerlang", answerLang.toString());
	    
	    return db.insert("sets", null, newSetValues);
	}
	
	public boolean updateSet(int id, String name, String questionLang, String answerLang) {
	    ContentValues updateSetValues = new ContentValues();
	    
	    String where = "_id" + "=" + id;
	    updateSetValues.put("name", name);
	    updateSetValues.put("questionlang", questionLang.toString());
	    updateSetValues.put("answerlang", answerLang.toString());
	    
	    return db.update("sets", updateSetValues, where, null) > 0;
	}
	
	public boolean deleteSet(int id){
	    String where = "_id" + "=" + id;	    
	    return db.delete("sets", where, null) > 0;
	}
	
	public Cursor getAllSets() {
	    String[] columns = { "_id", "name", "questionlang", "answerlang" };
	    return db.query("sets", columns, null, null, null, null, null);
	}
	 
	public SetTasks getSet(int id) {
		String where = "_id" + "=" + id;
		String[] columns = { "_id", "name", "questionlang", "answerlang" };
	    Cursor cursor = db.query("sets", columns, where, null, null, null, null);
	    SetTasks task = null;
	    
	    if(cursor != null && cursor.moveToFirst()) {
	        String name = cursor.getString(NAME_COLUMN);
	        String questionLang = cursor.getString(QUESTIONLANG_COLUMN);
	        String answerLang = cursor.getString(ANSWERLANG_COLUMN);
	        task = new SetTasks(id, name, questionLang, answerLang);
	    }
	    return task;
	}
   
}